<template>
  <div>
    <van-nav-bar v-if="goods.length>0" class="editVAN">
      <van-button slot="right" type="primary" size="small" plain hairline @click="editAddress" v-if="!editMode">编辑</van-button>
      <van-button slot="right" type="danger" size="small" plain hairline @click="deleCart" v-else>删除</van-button>
    </van-nav-bar>
    <div v-if="goods.length>0" class="cartList">
      <div v-for="(item,index) in goods" :key='index'>
        <div class="van-card__header">
          <van-checkbox
            :value="SelectItem[index]"
            checked-color="#07c160"
            class="ck_boxItem"
            name="Item"
            @change="onChangeItem(index,item.id)"
          >
          </van-checkbox>
          <div class="van-card__thumb">
            <image
              :src="item.image[0]"
              class="van-card__img thumb-class"
            />
          </div>
          <div class="van-card__content">
            <div class="van-card__title">{{item.title}}</div>
            <div class="van-card__desc desc-class">{{item.desc}}</div>
            <div class="van-card__bottom">
                <div class="van-card__price price-class"><van-icon name="balance-o" />{{item.price}}</div>
                <div class="van-card__num num-class">
                  <van-stepper
                    @change="changeStep"
                    class="stepper"
                    :value="item.goods_number"
                    integer
                    :id="index"
                    min="1"
                    step="1"
                    overlay="true"
                    slot="button"
                  />
                </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="nodata" v-else>
      <van-row>
        <van-col span="24">
          <van-icon custom-class="notIOCN" class="notIOCNWarp" name="shopping-cart-o" />
          <div class="notTXT">暂无数据</div>
        </van-col>
      </van-row>
    </div>
    <van-toast id="van-toast" />
    <van-submit-bar  
      v-if="goods.length>0"
      class="Cart_bar"
      button-class="barTools"
      button-text="提交"
      @submit="onSubmit"
      button-type="primary"
    >
      <van-checkbox
        :value="allSelect"
        checked-color="#07c160"
        class="ck_box"
        @change="selectAll"
        :tip="true"
      >
        全选
      </van-checkbox>
      <div slot="tip">
        您的收货地址不支持同城送, <text>修改地址</text>
      </div>
      <div class="bar__text">
        <span>合计：</span>
        <span class="bar__price"><van-icon name="balance-o" />{{allPrice}}</span>
      </div>
    </van-submit-bar>
  </div>
</template>
<script>
import Toast from '../../../static/vant/toast/toast.js'
import {integral, views} from '../../utils/utils.js'
export default {
  onShareAppMessage (res) {
    if (res.from === 'button') {
      // 增加积分
      this.sharpePage(this.$root.$mp.query.id, 3)
    } else {
      this.sharpePage(this.$root.$mp.query.id, 4)
    }
    return {
      title: '购物车',
      imageUrl: '/images/a.png',
      path: '/pages/cart/main',
      withShareTicket: true
    }
  },
  onShow: function () {
    if (this.$root.$mp.query.type !== undefined) {
      wx.setStorageSync('type', this.$root.$mp.query.type)
    }
    this.allSelect = false
    let issel = []
    this.SelectItem.forEach(element => {
      issel.push(false)
    })
    this.SelectItem = Object.assign(this.SelectItem, issel)
    // 获取购车列表
    let _this = this
    let userDtr = wx.getStorageSync('userDtr')
    if (userDtr !== '') {
      wx.request({
        url: _this.apiUrl + 'api/cart/list?uid_str=' + userDtr,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'GET',
        dataType: 'json',
        success: res => {
          if (res.data.code === 200) {
            _this.goods = Object.assign([], res.data.data)
            this.SelectItem.splice(0, this.SelectItem.length)
            this.orderList = []
            _this.goods.forEach(element => {
              this.SelectItem.push(false)
              this.orderList.push(element.id)
            })
            // 计算总价格
            _this.countAllPrice()
          }
        },
        fail: () => {},
        complete: () => {}
      })
    } else {
      wx.showToast({
        title: '未登录！',
        icon: 'none',
        duration: 2000
      })
      wx.navigateTo({ url: '/pages/my/main' })
    }
  },
  data () {
    return {
      allSelect: false,
      editMode: false,
      SelectItem: [],
      orderList: [],
      stepperId: '',
      allPrice: 0,
      goods: []
    }
  },
  components: {
  },
  computed: {},
  methods: {
    // 积分增加， 更新 分享、浏览 、转发数量，增加积分
    // type:share 更新分享数   views  更新浏览数 forwarding 更新转发数
    getIntegral (type = 2) {
      let _this = this
      let id = _this.$root.$mp.query.id
      // 增加积分
      integral(id, type)
      // 增加统计数量  views
      views(id, 'views')
    },
    // 1.签到 2.阅读文章 3.转发文章 4.分享小程序
    sharpePage (id, type = 3) {
      // 增加积分
      integral(id, type)
      // 增加统计数量 share
      views(id, 'share')
    },
    // 删除商品
    deleCart () {
      this.editMode = !this.editMode
      let ids = []
      this.SelectItem.forEach((element, index) => {
        if (element) {
          ids.push(this.goods[index].id)
        }
      })
      this.deleItem(ids.toString(), ids.length)
    },
    // 编辑模式
    editAddress (event) {
      this.editMode = !this.editMode
    },
    // 改变数量
    changeStep (value) {
      let _this = this
      this.stepperId = value.mp.target.id
      let newNumber = value.mp.detail
      this.countAllPrice()
      Toast.setDefaultOptions.duration = 500
      let userDtr = wx.getStorageSync('userDtr')
      wx.request({
        url: this.apiUrl + 'api/cart/update?uid_str=' + userDtr + '&cart_id=' + this.goods[this.stepperId].id + '&goods_number=' + newNumber,
        success (res) {
          let data = res.data
          if (data.code === 200) {
            _this.goods[_this.stepperId].goods_number = newNumber
          }
        }
      })
    },
    // 计算价格
    countAllPrice () {
      this.allPrice = 0
      this.SelectItem.forEach((element, index) => {
        if (element) {
          this.allPrice += this.goods[index].price * this.goods[index].goods_number
        }
      })
    },
    // 全选
    selectAll (value) {
      this.allSelect = !this.allSelect
      if (this.allSelect) {
        this.SelectItem.forEach((element, index) => {
          this.SelectItem[index] = true
        })
      } else {
        this.SelectItem.forEach((element, index) => {
          this.SelectItem[index] = false
        })
      }
      this.countAllPrice()
    },
    // 单选
    onChangeItem (index, id) {
      let at = !this.SelectItem[index]
      this.SelectItem.splice(index, 1, at)
      this.countAllPrice()
    },
    // 提交订单
    onSubmit () {
      let ids = []
      this.SelectItem.forEach((element, index) => {
        if (element) {
          ids.push(this.orderList[index])
        }
      })
      if (ids.length > 0) {
        wx.navigateTo({ url: '/pages/order/main?id=' + ids.toString() + '&type=cart' })
      } else {
        wx.showToast({
          title: '请选择商品兑换!',
          icon: 'none',
          duration: 2000
        })
      }
    },
    // 删除购车商品
    deleItem (id, length) {
      let _this = this
      let userDtr = wx.getStorageSync('userDtr')
      wx.request({
        url: _this.apiUrl + 'api/cart/del',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          'uid_str': userDtr,
          'cart_id': id
        },
        success (res) {
          let data = res.data
          if (data.code === 200) {
            _this.SelectItem.forEach((element, index) => {
              if (element) {
                _this.goods.splice(index, length)
                _this.SelectItem.splice(index, 1)
                index = index - 1
              }
            })
            wx.showToast({
              title: '删除成功!',
              icon: 'none',
              duration: 2000
            })
          }
        },
        fail: () => {},
        complete: () => {}
      })
    }
  },
  mounted () {}
}
</script>
<style scoped>
.cartList {
  margin-top:50px;
  margin-bottom: 100px;
}
.editVAN {
  position:fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 50px;
  z-index: 999;
}
.stepper {
  margin: 0 10px;
  float: right;
  margin: 5px 0;
}
.deletBtn{
  width: 65px;
  background-color: #f44;
  color: #fff;
  height: 100%;
  line-height: 80px;
  text-align: center;
  vertical-align: middle;
}
.barTools {
  color: #fff;
  background-color: #49a16f;
  border: 1px solid #49a16f;
}
.ck_box {
  margin:0 15px;
  display:inline-block;
}
.ck_boxItem {
  margin: 30px 0 0 5px;
  flex: 1;
  height:20px;
  width:20px;
  display:inline-block;
}
.ck_boxItem .van-checkbox {
  padding: 5px;
}
.van-submit-bar__bar--safe {
  padding-bottom:0;
}
.item .username {
  font-size: 16px;
  float: left;
}
.item .mobile {
  font-size: 14px;
  line-height: 18rpx;
  margin: 20rpx 0 0 20rpx;
  color: #b3b3b3;
  float: left;
}
.item .b {
  width: 90%;
  margin-top: 10rpx;
  float: left;
}
.bar__text {
  font-weight: 700;
  text-align: right;
  color: #49a16f;
  padding-right: 12px;
  margin-left: 15px;
}
.bar__price {
  display: inline-block;
}
.bar__price span {
  display: block
}
.van-card {
  position: relative;
  padding: 5px 15px;
  font-size: 12px;
  color: #333;
  background-color: #fafafa;
  box-sizing: border-box
}
.van-card__header {
  display: flex;
  padding: 5px;
  position: relative;
}
.van-card__header--center {
  -webkit-align-items: center;
  align-items: center;
  -webkit-justify-content: center;
  justify-content: center
}

.van-card__thumb {
  position: relative;
  width: 90px;
  height: 90px;
  margin-right: 10px;
  -webkit-flex: none;
  flex: none
}

.van-card__thumb:empty {
  display: none
}

.van-card__img {
  width: 100%;
  height: 100%
}

.van-card__content {
  position: relative;
  min-width: 0;
  flex: 8
}

.van-card__desc,
.van-card__title {
  word-break: break-all
}

.van-card__title {
  font-weight: 700;
  line-height: 25px;
  overflow:hidden;
  text-overflow:ellipsis;
  display:-webkit-box;
  -webkit-box-orient:vertical;
  -webkit-line-clamp:2;
  min-height: 50px;
  overflow: hidden;
}

.van-card__desc {
  line-height: 20px;
  color: #7d7e80
}

.van-card__bottom {
  line-height: 20px
}

.van-card__price {
  display: inline-block;
  font-weight: 700;
  color: #49a16f;
  line-height: 40px;
  height: 40px;
}

.van-card__origin-price {
  display: inline-block;
  margin-left: 5px;
  font-size: 10px;
  color: #7d7e80;
  text-decoration: line-through
}

.van-card__num {
  float: right
}

.van-card__tag {
  position: absolute;
  top: 2px;
  left: 0
}

.van-card__footer {
  width: 100%;
  text-align: right;
  -webkit-flex: none;
  flex: none
}
</style>
